<template>
  <div class="addInfo-edit">
    <div class="add-tab">题目管理</div>
    <el-form
        ref="form"
        :model="form"
        :rules="rules"
        size="large"
        label-width="100px"
    >
      <el-form-item label-width="100">
        <el-button type="primary" plain size="large" @click="addSubjectBtn">
          添加题目
        </el-button>
      </el-form-item>
      <div class="list-item" v-for="(item, index) in form.list" :key="index">
        <el-button
            class="item-del"
            type="danger"
            icon="el-icon-delete"
            circle
            size="large"
            :disabled="form.list.length == 1"
            @click="deleteSubjectBtn(index)"
        ></el-button>
        <el-form-item
            label="题目标题"
            :prop="`list[${index}].pName`"
            maxleng="100"
            :rules="[
            { required: true, message: '请输入题目标题', trigger: 'blur' }
          ]"
        >
          <el-input
              v-model="item.pName"
              placeholder="请输入题目标题"
              clearable
              :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
        <el-form-item
            label="题目内容"
            :prop="`list[${index}].context`"
            maxleng="100"
            :rules="[
            { required: true, message: '请输入题目内容', trigger: 'blur' }
          ]"
        >
          <el-input
              v-model="item.context"
              type="textarea"
              placeholder="请输入题目内容"
              clearable
              :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>

        <el-form-item
            label="运行时间"
            :prop="`list[${index}].limit`"
            :rules="[
            { required: true, message: '请输入运行时间', trigger: 'change' }
          ]"
        >
          <el-input-number
              v-model="item.limit"
              :precision="2"
              :min="0.1"
              :max="8"
              placeholder="请输入运行时间"
              clearable
              :style="{ width: '100%' }"
          ></el-input-number>
        </el-form-item>


        <el-form-item :rules="[{ required: true, message: '请选择输入文件', trigger: 'change', type: 'array' }]"
                      label="输入数据" :prop="`list[${index}].inputFileList`">
          <el-upload   v-model:file-list="item.inputFileList"   :auto-upload="false">
            <el-button type="primary">添加输入数据</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item :rules="[{ required: true, message: '请选择输出文件', trigger: 'change', type: 'array' }]"
                      label="输入数据" :prop="`list[${index}].outputFileList`">
          <el-upload   v-model:file-list="item.outputFileList"  :auto-upload="false">
            <el-button type="primary">添加输出数据</el-button>
          </el-upload>
        </el-form-item>

      </div>
      <el-form-item size="small">
        <el-button type="primary" plain size="large" @click="submitForm" v-loading.fullscreen.lock="fullscreenLoading">提交</el-button>
        <el-button plain size="large" @click="refResFun">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ElMessage } from "element-plus";
import api from "../api/api.js";
import {readFileAsPromise} from "../utils/utils.js"
import Moment from 'moment';

export default {
  name: "AddProblem",
  components: {

  },
  data() {
    return {
      rules: {

      },
      fullscreenLoading: false,
      form: {
        list: [
          {
            pName: "",
            limit: "",
            context: "",
            submitTimes: "0",
            acTimes: "0",
            createTime: Moment().format("YYYY-MM-DD HH:mm:ss"),
            tests:[],
            testNum: "", // 交给后端填上这个字段
            inputFileList: [],
            outputFileList: [],
          }
        ]
      }
    };
  },
  methods: {
    // 添加题目
    addSubjectBtn() {
      let addParams = {
        pName: "",
        limit: "",
        context: "",
        createTime: Moment().format("YYYY-MM-DD HH:mm:ss"),
        tests: {}
      };
      this.form.list.push(addParams);
    },
    // 删除题目
    deleteSubjectBtn(index) {
      this.form.list.splice(index, 1);
    },
    // 添加数据
    addOptionsBtn(item) {
      let addParams = {
        input: "",
        output: ""
      };
      item.tests.push(addParams);
    },
    // 删除数据
    deleteOptionsBtn(item, subIndex) {
      item.tests.splice(subIndex, 1);
    },
    CheckFileListNumEqual() {
      for (var i = 0; i < this.form.list.length; i++)
      {
        if (this.form.list[i].inputFileList.length != this.form.list[i].outputFileList.length)
        {
          ElMessage.error('输入数据和输出数据数量不相等');
          return false; // 代表不相等
        }
      }
      return true; // 代表相等
    },
    CheckDescQuato() {
      for (var i = 0; i < this.form.list.length; i++)
      {
        this.form.list[i].pName = this.form.list[i].pName.replaceAll("'","''");
        this.form.list[i].context = this.form.list[i].context.replaceAll("'", "''");
      }
    },
    submitForm() {
      console.log(this.form.list);
      this.$refs.form.validate(valid => {
            if (!valid || !this.CheckFileListNumEqual())
            {
              ElMessage.error('提交失败');
              return;
            }
            this.CheckDescQuato(); // 处理单引号

            for (var i = 0; i < this.form.list.length; i++)
            {
              let newStr = this.form.list[i].context.replace(/\n|\r\n/g, "<br>");
              this.form.list[i].context = newStr;
            }
            // 加载弹窗动画
            this.fullscreenLoading = true;
            Promise.all(
                this.form.list.map(
                    item => {
                      return Promise.all([
                        Promise.all(item.inputFileList.map(inputFile => readFileAsPromise(inputFile.raw))),
                        Promise.all(item.outputFileList.map(outputFile => readFileAsPromise(outputFile.raw))),
                      ])
                          .then(( [inputFiles, outputFiles] ) => {
                            for(let i = 0; i < inputFiles.length; i++){
                              item.tests.push({
                                input: inputFiles[i],
                                output: outputFiles[i]
                              });
                            }
                            return true;
                          })
                    }
                )).then(() => {
              // 不上传 inputFileList 和 outputFileList
              // emmm 这大概一点也不优雅
              const postForm = {...this.form,
                list: this.form.list.map((item) => {
                  const clone  = Object.assign({}, item);
                  delete clone.outputFileList;
                  delete clone.inputFileList;
                  return clone;
                })}
              ElMessage.success('提交新题');

              api.AddProblem(postForm)
                .then((res) =>
                {
                    if (res)
                    {
                        if (res.status == '200')
                        {
                          setTimeout(() => {
                            this.fullscreenLoading = false;
                          }, 2000);
                          // 清空原来的内容
                          for (var i = 0; i < this.form.list.length; i++)
                          {
                              this.form.list[i].tests.splice(0, this.form.list[i].tests.length);
                          }
                        }
                    }
                })
            })
          }
      )},
    refResFun() {
      this.$refs.form.resetFields();
    },
  }
}
</script>

<style lang="scss" scoped>

.addInfo-edit {
  padding: 30px;
  .add-tab {
    font-weight: bold;
    margin-bottom: 30px;
  }
  .list-item {
    position: relative;
    width: 1200px;
    margin-bottom: 30px;
    padding: 20px 70px 20px 0;
    border: 1px solid #eee;
    border-radius: 4px;
    .item-del {
      position: absolute;
      right: -50px;
      top: 0;
    }
  }

  .options-wrap {
    padding-left: 30px;
    .options-btn {
      margin-left: 20px;
    }
    .options-item {
      position: relative;
      margin-top: 15px;
      padding-top: 15px;
      padding-right: 15px;
      border: 1px solid #eee;
      border-radius: 4px;
    }
  }
  .last-options-wrap {
    margin-bottom: 16px;
    .options-item {
      margin-left: 16px;
    }
    .item-del{
      top: 18px;
    }
  }
}


</style>
